﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net;
using System.Globalization;
using System.Threading;

namespace StockTradTest.Data
{
    //获取股票历史信息
    public class GetIndexHistory
    {
        public static List<Index> indexs; 
        public static string GetHistoryFromWeb(string indexCode, DateTime start, DateTime end, string type = "zs")
        {
            //https://q.stock.sohu.com/hisHq?code=zs_000001&start=20000101&end=20200624
            string url = string.Format(@"http://q.stock.sohu.com/hisHq?code={3}_{0}&start={1}&end={2}", indexCode, start.ToString("yyyyMMdd"),
                end.ToString("yyyyMMdd"), type);
            WebClient client = new WebClient();
            try
            {
                string value = client.DownloadString(url);
                return value;
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

}
        public static void PraseHistoryData(string value)
        {
            try
            {
                indexs = new List<Index>();
                value = value.Substring(21, value.Length - 46).Replace("\"", string.Empty);
                string[] stringSeparators = new string[] { "],[" };
                string[] IndexArray = value.Split(stringSeparators, StringSplitOptions.None);
                foreach (var item in IndexArray)
                {
                    //["2020-05-08","16.26","16.37","0.21","1.30%","16.21","16.52","499030","81672.91","0.25%"]
                    string[] dayIndex = item.Split(',');
                    Index index = new Index {
                    Date = int.Parse(dayIndex[0].Replace("-","")),
                    OpenPrice = double.Parse(dayIndex[1]),
                    ClosePrice = double.Parse(dayIndex[2]),
                    ChangePrice = double.Parse(dayIndex[3]),
                    ChangeRatio = double.Parse(dayIndex[4].Substring(0, dayIndex[4].Length - 2)),
                    LowPrice = double.Parse(dayIndex[5]),
                    HighPrice = double.Parse(dayIndex[6]),
                    TotalHand = int.Parse(dayIndex[7]),
                    TotalAmount = double.Parse(dayIndex[8]),
                    HandRate = dayIndex[9] == "-" ? 0:double.Parse(dayIndex[9].Substring(0, dayIndex[9].Length - 2))};
                    indexs.Add(index);
                }
                //升序
                indexs.Sort();
            }
            catch (WebException e)
            {
                //How do I capture this from the UI to show the error in a message box? 
                Console.WriteLine(e);
            }

        }

        //每日实时更新
        public static async IAsyncEnumerable<string> UpdateDayAsync(string code)
        {
            Base.CurrentIndexCode = code;
            DateTime lastDate = DateTime.Now.AddDays(-1).Date;

            while (await Funciton.IsHolidayByDate(lastDate))
            {
                yield return lastDate.ToShortDateString() + "非交易日\r\n";
                lastDate = lastDate.AddDays(-1);
                yield return "上一日为" + lastDate.ToShortDateString() + "\r\n";
            }
            Index lastDay = await Base.IndexDatabase.GetIndexAsync(int.Parse(lastDate.ToString("yyyyMMdd")));
            if (lastDay != null)
            {
                yield return code + "历史信息加载成功，最新日期" + lastDay.Date.ToString() + "\r\n";
                yield break;
            }
            yield return "历史信息获取中\r\n";
            string value = GetHistoryFromWeb(code, new DateTime(2000, 1, 1), DateTime.Now);
            if (value == null)
            {
                Thread.Sleep(500);
                value = GetHistoryFromWeb(code, new DateTime(2000, 1, 1), DateTime.Now);
                if (value == null) yield break;
            }

            yield return ("历史信息获取完毕\r\n");
            PraseHistoryData(value);
            yield return ("历史信息导入成功\r\n");
            if (indexs == null || indexs.Count == 0)
            {
                yield return ("数据有误，存储失败\r\n");
                yield break;
            }

            await Base.IndexDatabase.SaveAllIndexAsync(indexs);
            yield return ("指数数据保存成功\r\n");
            Index.IndexDic.TryGetValue(code, out string name);
            yield return ( name + "信息存储成功，最新时间" + DateTime.Now.ToShortDateString().ToString() + "\r\n");
        }


    }


}
